package org.blogwu.learn.designpattern.chapter8.lazy.v4;

/**
 * 注重延迟加载，加入volatile防止重排序
 */
public class LazyDoubleCheckSingleton {
    private LazyDoubleCheckSingleton() {

    }

    private static volatile LazyDoubleCheckSingleton lazySingleton;

    public static LazyDoubleCheckSingleton getInstance() throws InterruptedException {
        //外面做一层判断，是为了单例实例化后，不在需要进入同步方法了。 
        if (lazySingleton == null) {
            synchronized (LazyDoubleCheckSingleton.class) {
                if (lazySingleton == null) {
                    Thread.sleep(2000);
                    lazySingleton = new LazyDoubleCheckSingleton();
                }
            }
        }
        return lazySingleton;
    }


    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            try {
                System.out.println("t1:" + LazyDoubleCheckSingleton.getInstance());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                System.out.println("t2:" + LazyDoubleCheckSingleton.getInstance());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();
        t2.start();
    }

}
